new Vue({
	el: '#app',
	data() {
		return {
			url: '/api/config/auth',
			test: '/api/users/userInfo',
			isServer: '/api/config/home',
			authInfo: {
				km: null,
				domain: window.location.host,
				qq: null,
				key: null
			}
		}
	},
	methods: {
		fetchRequest(url, options = {}) {
			const defaultOptions = {
				method: 'GET',
				headers: {
					'Content-Type': 'application/json',
				},
				body: null,
			}

			const finalOptions = { ...defaultOptions, ...options }

			if (finalOptions.body && finalOptions.method.toUpperCase() === 'POST') {
				finalOptions.body = JSON.stringify(finalOptions.body)
			}

			return fetch(url, finalOptions)
				.then(response => {
					if (!response.ok) {
						throw response
					}
					const contentType = response.headers.get('content-type')
					if (contentType && contentType.includes('application/json')) {
						return response.json()
					}
					return response.text()
				})
				.catch(error => {
					console.error('Fetch error:', error)
					throw error
				})
		},
		async getUserInfo() {
			let that = this
			
			try {
				const result = await that.fetchRequest(this.test)

				if (result.code !== 200) {
					swal('请登录后在操作', '用户名: admin 密码: 123456', 'warning')
						.then(res => {
							location.href = '/admin/login.html'
						})
					return
				}
				return false
			} catch (error) {
				console.log(error)
				swal('服务器有误', '', 'error')
			}
		},
		async verifyAuthorization() {
			let that = this

			const { domain, km, qq } = that.authInfo

			if (!domain || !km || !qq) {
				that.authInfo = {
					km: null,
					domain: window.location.host,
					qq: null,
					key: null
				}
				return swal('如果是第一次验证，除了秘钥选项框，其他都不能为空!', '', 'info')
			}

			try {
				const result = await that.fetchRequest(that.url, {
					method: 'POST',
					body: that.authInfo
				})

				const { code, msg } = result

				if (code !== 200) {
					return swal(msg, '', 'warning')
				}

				swal(msg, '', 'success').then(function (res) {
					if (res) {
						location.reload()
					}
				})
			} catch (error) {
				swal('服务器有误', '', 'error')
			}
		},
		async validateDatabase() {
			let that = this
			try {
				const result = await that.fetchRequest(that.isServer, {
					method: 'POST'
				})

				const { code } = result

				if (code !== 200) {
					swal(code, '数据库连接失败, 请检查数据库配置!', 'warning').then(function (res) {
						if (res) {
							location.reload()
						}
					})
					return
				}

				swal(`${code}`, '数据库连接成功', 'success')
				that.getUserInfo()
			} catch (error) {
				if (error.status === 500) {
					swal(`${error.status}`, '数据库连接失败, 请检查数据库配置!', 'error').then(function (res) {
						location.reload()
					})
					return
				}
				
				swal(`${error.status}`, '服务器有误', 'error')
			}
		}
	},
	mounted() {
		let that = this

		that.validateDatabase()

		document.querySelectorAll('input').forEach(function (item) {
			item.setAttribute('autocomplete', 'off')
		})	
	}
})